import Vue from "vue"

// vuex
import Vuex from "vuex"
Vue.use(Vuex)

import modules from "./store-modules"
const store = new Vuex.Store({
  modules,
})

// router
import VueRouter from "vue-router"
Vue.use(VueRouter)

import routes from "./routes"
const router = new VueRouter({
  routes,
  mode: "history",
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { x: 0, y: 0 }
    }
  },
})

// mint-ui
import MintUI from "mint-ui"
import "mint-ui/lib/style.css"
Vue.use(MintUI)

// app specific components
import Components from "./components"
Vue.use(Components)

// filter
import api from "$api"
import util from "$util"
Vue.filter("Money", (value) => {
  if (typeof value === "string") {
    value = parseFloat(value)
  }
  return value.toFixed(2)
})
Vue.filter("Date", (date, option) => {
  return util.transformDate(date)
})
Vue.filter("Enum", (value, entity, field) => {
  let Enum = api.Enum
  if (!Enum[entity] ||
    !Enum[entity][field] ||
    !Enum[entity][field].value
  ) {
    console.log(`${value} is an unknown enum`)
    return value
  }
  return Enum[entity][field].value[value]
})

// directive
Vue.directive("scroll", {
  inserted(el, binding) {
    let f = function(e) {
      if (binding.value(e, el)) {
        el.removeEventListener("scroll", f)
      }
    }
    el.addEventListener("scroll", f)
  },
})
Vue.directive("focus", {
  inserted(el) {
    el.focus()
  },
})

document.addEventListener("deviceready", function() {
  util.registerScanner((data) => {
    let elem = document.activeElement
    if (elem.tagName === "INPUT") {
      elem.value = data
    }
  })
}, false)

const TTL = 10000

// root
import AppRoot from "./root/AppRoot.vue"
new Vue({
  router,
  store,

  el: "#app",
  render: (h) => h(AppRoot),

  data: {
    User: {
      id: 0,
      realName: "",
      token: "",
      permMap: {},

      IsLoggedIn: false,
    },

    ttl: TTL,

    IsBack: false,
    JustClickBack: false,
  },

  methods: {
    Back() {
      this.IsBack = true
      this.JustClickBack = true
      this.$router.back()
    },

    checkLoginStatus() {
      let user = util.loginInfo.getUser()
      if (!user) {
        this.IsLoggedIn = false
        return
      }
      if (user.createTime + user.maxAge < Date.now()) {
        this.IsLoggedIn = false
        return
      }

      // TODO
      this.User = {
        id: 101,
        realName: "张三",
        token: "aoeuaoeuaoe",
        IsLoggedIn: true,
      }
      api.setLoginToken = "aoeuaoeuao"

      /* api.AutoLogin({
          id: user.id,
        })
        .then((data) => {
          this.User = {
            id: user.id,
            realName: user.realName,
            token: user.token,
            IsLoggedIn: true,
          }
        })
        .catch((err) => {
          this.IsLoggedIn = false
        }) */
    },

    error(err, isCustom) {
      if (err.status === 401) {
        this.User.IsLoggedIn = false
        this.$router.replace("/")
        document.location.href = "index.html"
        return
      }
      if (isCustom) {
        return
      }
      if (err.msg) {
        util.Alert(err.msg)
      } else if (err.name === "TypeError") {
        console.log(err)
        util.Alert("客户端错误")
      } else if (err.name === "ReferenceError") {
        console.log(err)
        util.Alert("客户端错误")
      } else if (err.code === "ECONNABORTED") {
        util.Alert("请求超时，请检查网络连接")
      } else {
        util.Alert("服务器错误")
      }
    },
  },

  created() {
    this.checkLoginStatus()
    document.addEventListener("backbutton", this.Back, false)

    /* let INTERVAL = 1000
    document.addEventListener("deviceready", () => {
      setInterval(() => {
        this.ttl -= INTERVAL
        util.Toast(this.ttl.toString())
        if (this.ttl <= 0) {
          this.ttl = TTL
          this.User.IsLoggedIn = false
          this.$router.replace("/")
        }
      }, INTERVAL)

      document.addEventListener("click", () => {
        this.ttl = TTL
      })
    }) */
  },

  beforeDestroy() {
    document.removeEventListener("backbutton", this.Back, false)
  },
})
